<?php

namespace Admin\Controller;

use Think\Controller;
use Admin\Model\SystemModel;
use Admin\Model\RoleModel;

class BaseController extends Controller
{
    // 构造函数
    public function __construct()
    {
        parent::__construct();
        // 获取系统信息
        $this->getSystemInfo();

        // 登录判断
        if (!session('manage')) {
            $url = U('Login/login');
            echo "<script>top.location.href='" . $url . "'</script>";
            exit();
        }

        // 检查权限
        if (session('manage')['username'] !== "admin") {
            if (!$this->checkAuth()) {
                if (IS_AJAX) {
                    return retJson(1, "对不起，没有权限！");
                } else {
                    $html = '<div style="text-align: center; margin-top: 20%;">'
                        . '<h1 style="font-size: 72px; color: #e74c3c;">No permission!</h1>'
                        . '</div>';
                    exit($html);
                }
            }
        }
    }

    // 检查权限
    public function checkAuth()
    {
        $navList = C('NAV_LIST');
        $role = (new RoleModel)->getRoleById(session("manage")["role_id"]);
        $idString = $role["auth"];
        $auth_hrefs = getHrefs($navList, $idString);
        $ca_url  = CONTROLLER_NAME . "/" . ACTION_NAME; // 当前url
        $out_url = "Index/index,Index/main,Index/clearcache,Index/updpwd,Index/userinfo"; // 需要排除的url
        if (strpos($out_url, $ca_url) === false) {
            if (strpos($auth_hrefs, $ca_url) === false) {
                return false;
            }
        }
        return true;
    }

    // 获取系统信息
    public function getSystemInfo()
    {
        $sys_info = F('sys_info');
        if (!empty($sys_info)) {
            $this->assign("sys_info", $sys_info);
        } else {
            $system_model = new SystemModel();
            $data = $system_model->getSystemData();
            F('sys_info', $data);
            $this->assign("sys_info", $data);
        }
    }
}
